package com.st.buy.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.st.buy.manager.mapper.TbUserMapper;
import com.st.buy.pojo.TbUser;
import com.st.buy.sso.service.UserService;
import com.st.buy.util.json.JsonUtil;
import com.st.buy.util.pojo.BuyResult;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 张双虎
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private TbUserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public BuyResult check(String data, int type) {
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        if(type==1){
            wrapper.eq("username",data);
        }else if(type==2){
            wrapper.eq("phone",data);
        }else{
            throw new RuntimeException("参数有误：type应该是1或者2，单数传入了:"+type);
        }
        List<TbUser> users = userMapper.selectList(wrapper);
        BuyResult buyResult = BuyResult.ok();
        //如果查询到数据，说明重复了
        if(users!=null && users.size()>0){
            buyResult.setData(false);
        }else{
            buyResult.setData(true);
        }
        return buyResult;
    }

    @Override
    public BuyResult regist(TbUser user) {
        //补全信息
        user.setCreated(new Date());
        user.setUpdated(new Date());
        //密码是需要MD5加密  使用spring提供的工具类对密码进行MD5加密
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(password);
        //保存
        if(userMapper.insert(user)==1){
            return BuyResult.ok();
        }
        return BuyResult.err5x();
    }

    @Override
    public BuyResult login(String username, String password) {
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        List<TbUser> users = userMapper.selectList(wrapper);
        BuyResult result = BuyResult.ok();
        if(users==null || users.size()==0){
            result = BuyResult.err5x();
            result.setMsg("用户名或密码错误");
            return result;
        }
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!users.get(0).getPassword().equals(pwd)){
            result = BuyResult.err5x();
            result.setMsg("用户名或密码错误");
            return result;
        }
        //登录成功之后的操作
        //存储用户信息到redis
        //生成token  我们使用UUID生成
        String token = UUID.randomUUID().toString().replace("-","");
        //用户信息转成json存入redis
        stringRedisTemplate.opsForHash().put(token,"user", JsonUtil.object2json(users.get(0)));
        //设置key的存活时间
        stringRedisTemplate.expire(token,30, TimeUnit.MINUTES);
        //返回token  将token放在buyResult对象中返回。
        result.setData(token);
        return result;
    }

    @Override
    public BuyResult checkToken(String token) {
        BuyResult result = BuyResult.ok();
        //从redis中取数据
        String key = token;
        //判断key是否存在
        if(stringRedisTemplate.hasKey(key)){
            //判断用户是否存在
            if(stringRedisTemplate.opsForHash().hasKey(token,"user")){
                //获取用户信息
                String userJson = stringRedisTemplate.opsForHash().get(token, "user").toString();
                //将json转换为user
                TbUser user = JsonUtil.json2object(userJson,TbUser.class);
                //将user放入BuyResutl
                result.setData(user);
                //修改redis中数据的存活时间
                stringRedisTemplate.expire(token,30,TimeUnit.MINUTES);
                //如果查询到用户就直接返回
                return result;
            }
        }
        result.setStatus(404);
        return result;
    }
}
